package com.example.charges.activities.login;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.example.charges.R;
import com.example.charges.activities.home.HomeUtenteActivity;
import com.molinari.androidstructure.activity.BaseActivity;

public class LoginActivity extends BaseActivity {

	private Button btnSign;
	private EditText user;
	private EditText pass;
	private CheckBox utenteDefault = null;
	
	@Override
	protected int getIdLayout() {
		return R.layout.login;
	}

	@Override
	protected void onCreateCustom(Bundle savedInstanceState) throws Exception {
		btnSign = loadButton(btnSign, R.id.btnSign);
		utenteDefault = (CheckBox) load(utenteDefault, R.id.checkBoxUtenteDef);
		user = loadEdit(user, R.id.editPassord);
		pass = loadEdit(pass, R.id.editUsername);
		
		cercaUtenteDefault();
		
		btnSign.setOnClickListener(new OnClickBtnSignListener(HomeUtenteActivity.class, this));

		utenteDefault.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(((CheckBox)v).isChecked()){
					user = loadEdit(user, R.id.editUsername);
					pass = loadEdit(pass, R.id.editPassord);
					try {
						Editor edit = getPreferenceEditor("utenteDefault", MODE_PRIVATE);
						edit.clear();
						edit.putString("user", user.getText().toString());
						edit.putString("pass", pass.getText().toString());
						edit.commit();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	private void cercaUtenteDefault() {
		try {
			
			SharedPreferences preferences = getSharedPreferences("utenteDefault", MODE_PRIVATE);
			user.setText(preferences.getString("user", ""));
			pass.setText(preferences.getString("pass", ""));
			if(user.getText().toString() != null && !user.getText().toString().equals("")){
				utenteDefault.setChecked(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public int getIdMenu() {
		return R.menu.main;
	}

	public Button getBtnSign() {
		return btnSign;
	}

	public void setBtnSign(Button btnSign) {
		this.btnSign = btnSign;
	}

	public EditText getUser() {
		return user;
	}

	public void setUser(EditText user) {
		this.user = user;
	}

	public EditText getPass() {
		return pass;
	}

	public void setPass(EditText pass) {
		this.pass = pass;
	}

	public CheckBox getUtenteDefault() {
		return utenteDefault;
	}

	public void setUtenteDefault(CheckBox utenteDefault) {
		this.utenteDefault = utenteDefault;
	}

}
